package com.lemon.smartsafety.ui.activity.safe.data.safe_manager;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.Field;
import com.lemon.android.http.HttpUtils;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.common.EvidenceActionSheetType;
import com.lemon.smartsafety.entity.common.UploadFileItem;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.event.safe_manager.SafeItemRefreshEvent;
import com.lemon.smartsafety.entity.main.OptionItemVo;
import com.lemon.smartsafety.entity.safe.company.CompanyInfo;
import com.lemon.smartsafety.entity.safe.safe_manager.CompanySafeManageItemVo;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.SafeManagerItemServices;
import com.lemon.smartsafetynew.ui.activity.base.PhotoSelectBaseActivity;
import com.lemon.smartsafety.ui.adapter.common.SelectEvidenceAdapter;
import com.lemon.smartsafety.ui.adapter.safe.safe_manager.CheckResultAdapter;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.DateUtils;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.utils.photo.GlideImageLoader;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by Cooliean on 16/1/24.
 */
public class SafeManagerPropActivity extends PhotoSelectBaseActivity {


    @Bind(R.id.tv_title)
    TextView         tvTitle;
    @Bind(R.id.metRemark)
    MaterialEditText metRemark;
    @Bind(R.id.metLastCheck)
    MaterialEditText metLastCheck;
    @Bind(R.id.metLastResult)
    MaterialEditText metLastResult;
    @Bind(R.id.metResultSelect)
    MaterialEditText metResultSelect;
    @Bind(R.id.rowResultSelect)
    TableRow         rowResultSelect;
    @Bind(R.id.metCheckRemark)
    MaterialEditText metCheckRemark;

    @Bind(R.id.iv_photo1)
    ImageView ivPhoto1;
    @Bind(R.id.iv_photo2)
    ImageView ivPhoto2;
    @Bind(R.id.iv_photo3)
    ImageView ivPhoto3;
    @Bind(R.id.rowPhotoOld)
    TableRow  rowPhotoOld;


    @Bind(R.id.btn_submit)
    Button btnSubmit;


    private LoggerHelper loggerHelper = new LoggerHelper(SafeManagerPropActivity.class);

    private CompanySafeManageItemVo mSafeVo;

    private CompanyInfo mCompanyInfo;

    private OptionItemVo mSelectResult = null;

    private List<OptionItemVo> resultList = new ArrayList<>();

    private boolean isEdit = false;


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            mCompanyInfo = (CompanyInfo) getIntent().getSerializableExtra(BundleKey.COMPANY_INFO);
            mSafeVo = (CompanySafeManageItemVo) getIntent().getSerializableExtra(BundleKey.SAFE_MANAGER_ITEM);
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_safe_manager_setting_prop;
    }

    @Override
    protected void initViews() {
        super.initViews();
        setMaxSize(3);

        if (mSafeVo != null) {
            initEditView(mSafeVo);
        }
    }


    @Override
    protected void initTitle() {
        this.setBarTitle(R.string.safe_manager_prop);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
     /*   super.onCreateOptionsMenu(menu);
        boolean menuResult = super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_history, menu);
        return menuResult;
*/
        getMenuInflater().inflate(R.menu.menu_history, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_history) {
            //历史记录
            LoggerHelper.error(SafeManagerPropActivity.class,"历史记录");
            Bundle bundle = new Bundle();
            bundle.putSerializable(BundleKey.COMPANY_INFO, mCompanyInfo);
            bundle.putSerializable(BundleKey.SAFE_MANAGER_ITEM, mSafeVo);
            UIHelper.showActivity(this, bundle, SafeManagerHistoryListActivity.class);
            //startActivity(new Intent(this,SafeManagerHistoryListActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(SafeManagerPropActivity.class);
    }


    @Override
    protected void initListener() {
        super.initListener();
    }


    /**
     * 表单验证
     *
     * @return
     */
    private boolean validateForm() {
        /**
         * 检查部位
         */
        if (mSelectResult == null) {
            metResultSelect.setError(getString(R.string.safe_manager_pick_result));
            mHUDUtil.showErrorTip(getString(R.string.safe_manager_pick_result));
            return false;
        }

        return true;
    }

    @OnClick(R.id.btn_submit)
    protected void btnSubmitAction() {
        if (!validateForm()) {
            return;
        }
        getConfirmDialog(getString(R.string.is_submit), new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    doPostAction();
                }
            }
        }).show();

    }

    private void doPostAction() {
        final LemonRequestParams params = new LemonRequestParams("company_safe_manage_record", "record_id", "");

        if (isEdit) {
            params.put("_txtIdValues", "");
            params.put("record_id", "");
        } else {
            params.put("_txtIdValues", "");
            params.put("record_id", "");
        }
        params.put("user_id", mSharedPreferencesHelper.getUserId());
        //params.put("txtCheckPart", txtCheckPart, Field.TYPE_STRING);

        /*
            [params putObjectForKey:@"company_code" object:self.company.company_code];
            [params putObjectForKey:@"txtItemId" object:self.safeItemVo.item_id type:TYPE_INT];
            [params putObjectForKey:@"txtCheckTime" object:[CLDateUtil nowDataYYYYMMDDHHMMSS] type:TYPE_DATE];
            [params putObjectForKey:@"txtCheckUser" object:GET_USER_NAME type:TYPE_STRING];
            [params putObjectForKey:@"txtRemark" object:[self.form formRowWithTag:@"check_remark"].value type:TYPE_STRING];
         */
        params.put("company_code", StringUtils.nullValue(mCompanyInfo.getCompany_code()));
        params.put("txtItemId", mSafeVo.getItem_id(), Field.TYPE_INT);
        params.put("txtCheckTime", DateUtils.getCurrentYMDHMSDate(), Field.TYPE_DATE);
        params.put("txtCheckUser", mSharedPreferencesHelper.getUserName(), Field.TYPE_STRING);
        params.put("txtRemark", metRemark.getText().toString().trim(), Field.TYPE_STRING);
        String result = String.format("%s,%s", StringUtils.nullValue(mSelectResult.getVoId()), StringUtils.nullValue(mSelectResult
                                                                                                                             .getTitle()));
        params.put("txtCheckResult", result, Field.TYPE_STRING);

        getUploadItems(new SelectEvidenceAdapter.CropCallBack<List<UploadFileItem>>() {
            @Override
            public void onStart() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mHUDUtil.showHUD();
                    }
                });
            }

            @Override
            public void onFinish(List<UploadFileItem> data) {
                if (data != null && data.size() != 0) {
                    for (int i = 0; i < data.size(); i++) {
                        if (i == 0) {
                            params.put("picture1", data.get(i).getBase64());
                        } else if (i == 1) {
                            params.put("picture2", data.get(i).getBase64());
                        } else if (i == 2) {
                            params.put("picture3", data.get(i).getBase64());
                        }
                    }
                }
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        SafeManagerItemServices.init().saveSafeManagerItemAction(params, isEdit);
                    }
                });
            }
        });
    }


    /**
     * 处理所有的网络请求返回
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final HttpCallbackEvent event) {
        if (EventTag.TAG_SAFE_MANAGER_SAVE_ACTION == event.getTag()) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.show();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            SafeItemRefreshEvent refreshEvent = new SafeItemRefreshEvent();
                            refreshEvent.setTag(SafeItemRefreshEvent.class.getName());
                            AppService.getBus().post(refreshEvent);
                            AppManager.getAppManager().finishActivity(SafeManagerPropActivity.this);
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHUDUtil.hidden();
    }

    private void initEditView(CompanySafeManageItemVo data) {
        if (null == data) return;

        tvTitle.setText(StringUtils.nullValue(data.getItem_name(), ""));
        metRemark.setText(String.format("%s", StringUtils.nullValue(data.getRemark(), "--")));
        metLastCheck.setText(String.format("%s %s", StringUtils.nullValue(data.getLast_check_user(), "--"), DateUtils.getFormatDateStringWithDateString(data.getLast_check_time(), DateUtils.dateFormatYMDHM)));

        String lastResult = StringUtils.nullValue(data.getCheck_result(), "--");
        if (lastResult.indexOf(",") != -1) {
            lastResult = lastResult.substring(lastResult.indexOf(",") + 1);
        }
        metLastResult.setText(lastResult);


        if (StringUtils.nullValue(data.getPicture1()).length() != 0) {
            final String url = HttpUtils.formatFilesUrl(data.getPicture1());
            ivPhoto1.setVisibility(View.VISIBLE);
            ivPhoto1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PhotoInfo info = new PhotoInfo();
                    info.setPhotoPath(url);
                    UIHelper.showPhotoView(SafeManagerPropActivity.this, info);
                }
            });
            GlideImageLoader.loadImage(this, url, ivPhoto1);
        }else{
            ivPhoto1.setVisibility(View.GONE);
        }

        if (StringUtils.nullValue(data.getPicture2()).length() != 0) {
            final String url = HttpUtils.formatFilesUrl(data.getPicture2());
            ivPhoto2.setVisibility(View.VISIBLE);
            ivPhoto2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PhotoInfo info = new PhotoInfo();
                    info.setPhotoPath(url);
                    UIHelper.showPhotoView(SafeManagerPropActivity.this, info);
                }
            });
            GlideImageLoader.loadImage(this, url, ivPhoto2);
        }else{
            ivPhoto2.setVisibility(View.GONE);
        }

        if (StringUtils.nullValue(data.getPicture3()).length() != 0) {
            final String url = HttpUtils.formatFilesUrl(data.getPicture3());
            ivPhoto3.setVisibility(View.VISIBLE);
            ivPhoto3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PhotoInfo info = new PhotoInfo();
                    info.setPhotoPath(url);
                    UIHelper.showPhotoView(SafeManagerPropActivity.this, info);
                }
            });
            GlideImageLoader.loadImage(this, url, ivPhoto3);
        }else{
            ivPhoto3.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.metResultSelect, R.id.rowResultSelect})
    public void onClick(View view) {
        showDialog(getResultList(mSafeVo.getItem_options()));
    }

    private List<OptionItemVo> getResultList(String result) {
        resultList = new ArrayList<>();
        if (StringUtils.nullValue(result).length() != 0) {
            String[] arrs = result.split(",");
            if (arrs != null && arrs.length != 0) {
                for (int i = 0; i < arrs.length; i = i + 2) {
                    OptionItemVo vo = new OptionItemVo();
                    vo.setTitle(arrs[i + 1]);
                    vo.setVoId(arrs[i]);
                    resultList.add(vo);
                }
            }
        }
        return resultList;
    }


    private void showDialog(List<OptionItemVo> items) {
        new MaterialDialog.Builder(this).title(R.string.safe_manager_pick_result)
                                        .adapter(new CheckResultAdapter(items), new MaterialDialog.ListCallback() {
                                            @Override
                                            public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                                mSelectResult = resultList.get(which);
                                                metResultSelect.setText(mSelectResult.getTitle());
                                                dialog.dismiss();
                                            }
                                        })
                                        .show();
    }


    @Override
    public void evidencePlusEventHandler(String tag) {
        if (mPhotoList.size() >= 4 && mHUDUtil != null) {

            mHUDUtil.showErrorTip("最多只能选择3张图片信息");
            return;
        }
        if (this.getClass().getName().equals(tag)) {
            showActionSheet(EvidenceActionSheetType.CAMERA_ALBUM_MULTI);
        }
    }

}
